<template>
  <el-drawer
    :model-value="modelValue"
    @close="updateVisible"
    @opened="handleDrawerOpen"
  >
    <!-- 头部选项卡 -->
    <template #header>
      <div class="tab-container">
        <div
          class="choose-tab"
          v-for="tab in systemUpdateTabs"
          :key="tab.id"
          :class="{ 'choose-tab-active': tab.id === serachForm.tabId }"
          @click="switchTab(tab.id)"
        >
          <div class="tab-item">
            <i class="iconfont" :class="tab.icon"></i>
            <span>{{ tab.label }}</span>
          </div>
        </div>
      </div>
    </template>
    <!-- 内容 -->
    <template #default>
      <!-- 抽屉内容 -->
      <div class="content" v-loading="loading">
        <div class="left-content">
          <!-- 此处v-if="serachForm.tabId == 2"是因为其他tab没接口，暂时不做，开发的时候去掉 -->
          <div class="tabshow-title" v-if="serachForm.tabId == 2">
            <div class="search-left">
              <div
                class="left-box"
                :class="{ isChangeWidth: inputStyle.width === '80%' }"
              >
                <div v-if="serachForm.tabId !== 2">
                  <el-input
                    v-model="serachForm.keywords"
                    size="large"
                    ref="searchInput"
                    placeholder="搜索"
                    :prefix-icon="Search"
                    @click="handleClick"
                    :style="inputStyle"
                    @input="handleChange"
                  />
                  <!-- 当输入框宽度为 80% 时显示取消按钮 -->
                  <div
                    v-if="inputStyle.width === '80%'"
                    class="cancel-button"
                    @click.stop="resetInputWidth"
                  >
                    取消
                  </div>
                </div>
                <div v-else>
                  <el-select
                    v-model="serachForm.status"
                    placeholder="全部"
                    size="large"
                    style="width: 100px"
                    @change="fetchData"
                    clearable
                  >
                    <el-option
                      v-for="item in WORKER_STATUS"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id"
                    />
                  </el-select>
                </div>
              </div>
              <div class="flex right-box" v-if="inputStyle.width !== '80%'">
                <el-select
                  v-if="serachForm.tabId !== 2"
                  v-model="serachForm.status"
                  placeholder="全部"
                  :readonly="true"
                  size="large"
                  class="all"
                  @change="fetchData"
                  clearable
                >
                  <el-option
                    v-for="item in STATUS_OPTIONS"
                    :key="item.id"
                    :label="item.value"
                    :value="item.id"
                  />
                </el-select>
                <!-- style="display: none"功能为开发，先写style="display: none"，开发的时候打开 -->
                <div class="flex f14 allRead" style="display: none">
                  <i class="iconfont icon-yidu"></i>
                  全部已读
                </div>
              </div>
            </div>
          </div>
          <ListComponent
            :formattedList="formattedList"
            :loading="loading"
            :loadMore="loadMore"
            @handleClickItem="handleClickItem"
          />
        </div>
        <div class="right-content" :class="{ 'r-nodata': isEmptyData }">
          <div class="haveData" v-if="!isEmptyData">
            <div class="data" v-if="serachForm.tabId !== 2">
              <div class="title">{{ selectedInfo.name }}</div>
              <!-- 数据更新和版本更新 -->
              <div
                class="content rich-text"
                v-html="selectedInfo.content"
              ></div>
            </div>
            <!-- 工单通知 -->
            <div class="data" v-else>
              <h3 class="title">
                工单：{{ selectedInfo.orderNo }}已处理完成。
              </h3>
              <div v-for="item in WORKERFIELDS" :key="item.key">
                <div class="item">
                  <span class="gong-dan-title"> {{ item.label }}:</span>
                  <span
                    :class="[
                      'workorder-status',
                      item.key == 'status'
                        ? 'workorder-status-' + selectedInfo['status']
                        : '',
                      item.key == 'remark' || item.key == 'auditRemark'
                        ? 'auditRemark'
                        : '',
                    ]"
                  >
                    {{
                      (item.format
                        ? item.format(selectedInfo[item.key])
                        : selectedInfo[item.key]) || '-'
                    }}</span
                  >
                </div>
              </div>
            </div>
          </div>
          <div class="noDat" v-else>
            <img class="imgs" src="@/assets/images/no-data.png" alt="" />
            <p>点击左侧 查看详情</p>
          </div>
        </div>
      </div>
    </template>
  </el-drawer>
</template>

<script setup lang="tsx">
import { ref, reactive, nextTick, computed, PropType, watch } from 'vue';
import { TabItem } from '@/types/dashboard/index';
import { ApiData } from '@/types/dashboard/updateLog'; // 引入类型定义
// 将不同选项卡api请求到的数据列表，处理成相同的字断，进行统一渲染
import { getMapper, WORKERFIELDS } from './dataFormatter';
import { Search } from '@element-plus/icons-vue';
import { ElInput } from 'element-plus'; // 引入 ElInput 组件
import ListComponent from './listComponent.vue'; // 引入列表组件
import { omit, isEmpty, debounce } from 'lodash';
import dashboard from '@/modules';
// getApiConfig选项卡api，TABLECONFIG：表格配置，WORKERSTATUS：工单处理回执状态
const { getApiConfig, TABLECONFIG, STATUS_OPTIONS, WORKER_STATUS } = dashboard;
// 发送更新事件
const emit = defineEmits(['update:modelValue']);

// 定义 props
const props = defineProps({
  modelValue: {
    type: Boolean,
    required: true,
  },
  systemUpdateTabs: {
    type: Array as PropType<TabItem[]>,
    required: true,
  },
  drawerInfo: {
    type: Object,
    default: () => {},
  },
});

// 选中的列表信息-右侧回显
const selectedInfo: any = ref({});
// 加载动画
const loading = ref(false);
// 表格数据
const tableData = ref<ApiData[]>([]);
// 是否最后一页
const lastpage = ref(false);
// 表格配置
const tableConfig = ref({
  page: 1,
  pageSize: 20,
});
// 是否空数据
const isEmptyData = computed(() => isEmpty(selectedInfo.value));
// 搜索 input 的 ref
const searchInput = ref<InstanceType<typeof ElInput> | null>(null);
// 抽屉打开时自动选中输入框
const handleDrawerOpen = () => {
  fetchData();
  nextTick(() => {
    if (searchInput.value) {
      searchInput.value.focus();
      searchInput.value.select();
    }
  });
};
// 初始样式
const inputStyle = reactive({
  width: '125px',
  transition: 'width 0.5s ease',
});
// 点击事件处理
const handleClick = () => {
  searchInput.value?.focus();
  inputStyle.width = '80%'; // 设置宽度为 80%
};
// 点击取消按钮时恢复宽度为 125px
const resetInputWidth = () => {
  inputStyle.width = '125px'; // 恢复宽度为 125px
};
// 搜索部分
const serachForm = reactive({
  keywords: '',
  status: '',
  tabId: 1,
  statusList: WORKER_STATUS,
});
// 更新抽屉开关，避免关闭无法打开
const updateVisible = () => {
  serachForm.tabId = 1;
  resetForm(serachForm.tabId);
  emit('update:modelValue', false);
};
// 选项卡切换
const switchTab = (id: string | number) => {
  resetForm(id);
  fetchData(); // 切换选项卡后重新获取数据
};
// 清除搜索项
const resetForm = (id: any) => {
  inputStyle.width = '125px';
  lastpage.value = false;
  serachForm.keywords = '';
  serachForm.status = '';
  serachForm.tabId = id;
  tableData.value = [];
  selectedInfo.value = {};
  tableConfig.value = { ...TABLECONFIG };
};
// 多个选项卡处理成相同的字断和数据结构
const formattedList = computed(() => {
  const mapper = getMapper(serachForm.tabId);
  return Array.isArray(tableData.value) ? tableData.value.map(mapper) : [];
});
// 设置 500 毫秒的防抖间隔-输入框搜索
const handleChange = debounce(() => {
  fetchData();
}, 500);
// 请求数据
const fetchData = async (e: any = '') => {
  // e来自于下拉框状态切换，就先清空
  if (e) tableData.value = [];
  loading.value = true;
  // 获取对应选项卡的api地址和接口
  const { apiFunc, url } = getApiConfig('HOMESYSTEMDRAWER', serachForm.tabId);
  try {
    const isWorker = serachForm.tabId == 2;
    const { data } = await apiFunc(
      url,
      omit(
        {
          ...serachForm,
          ...tableConfig.value,
          type: serachForm.tabId,
        },
        ['statusList', isWorker ? 'type' : '']
      )
    );
    // 是否为最后一页
    lastpage.value = data.last_page == tableConfig.value.page;
    // 拼接数据
    tableData.value = [...tableData.value, ...data.data];
  } catch (error) {
    console.error('数据请求失败:', error);
    tableData.value = []; // 发生错误时清空数据
  } finally {
    loading.value = false; // 无论成功还是失败，关闭加载动画
  }
};
// 下拉加载
const loadMore = async () => {
  // 正式掉接口放开
  if (lastpage.value) return; // 防止重复加载或已无更多数据
  tableConfig.value.page += 1;
  await fetchData();
};

// 点击左侧
const handleClickItem = (id: string | number) => {
  const selectedItem: any = tableData.value.filter((item) => item.id === id)[0];
  if (selectedItem) {
    selectedInfo.value = { ...selectedItem }; // 或者其他字段
  }
};

watch(
  () => props.drawerInfo,
  (newValue) => {
    selectedInfo.value = newValue;
  }
);
</script>

<style lang="scss" scoped src="./drawer.scss"></style>
